package com.unis.controller.system;

import java.util.HashMap;
import java.util.List;

import com.unis.common.secure.authc.UserInfo;
import com.unis.logger.TargetLogger;
import com.unis.model.system.DwDzz;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.util.Map;

import com.unis.dto.ResultDto;
import com.unis.common.exception.http.RequestEntityTooLargeException;
import com.unis.common.excel.ExportBeanExcel;
import com.unis.common.util.ValidateUtil;

import com.unis.controller.BaseController;
import com.unis.model.system.Jgz;
import com.unis.service.system.JgzService;

/**
 * @author xuk
 * @version 1.0
 * @since 2019-01-31
 */
@Controller
@RequestMapping("/system/jgz")
public class JgzController extends BaseController {
	private static final Logger logger = LoggerFactory.getLogger(JgzController.class);

    @Autowired
    private JgzService jgzService;

    @RequestMapping("/page")
    public String forwordPage()  {
        return "system/jgz/jgzPage";
    }

    @TargetLogger("06020401")
    @RequiresPermissions("ROLE_VIEW")
    @RequestMapping( "/list")
    @ResponseBody
    public ResultDto queryJgzList(@RequestParam Map<?, ?> paramMap){
    	int pageSize = paramMap.get("pageSize")==null ? 10 : Integer.parseInt(paramMap.get("pageSize").toString());
        int pageNumber = paramMap.get("pageNumber")==null ? 1 : Integer.parseInt(paramMap.get("pageNumber").toString());
        try {
            ResultDto page = jgzService.queryListByPage(paramMap,pageNumber,pageSize);
            return page;
        } catch (Exception e) {
            logger.error(e.getMessage());
            throw new RequestEntityTooLargeException(e.getMessage());
        }
    }

    @RequestMapping("/checkJgz")
    @ResponseBody
    public String checkJgz(String dwdm) {
        Jgz jgz = new Jgz();
        if(StringUtils.isNotBlank(dwdm)){
            jgz.setDwdm(dwdm);
        }else{
            UserInfo userInfo = jgzService.getUserInfo();
            jgz.setUserpk(userInfo.getPk());
        }
        try {
            jgz = jgzService.queryAsObject(jgz);
            if (jgz!=null){
                return "true";
            }else{
                return "false";
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
            throw new RequestEntityTooLargeException(e.getMessage());
        }
    }
    @RequestMapping("/getJgz")
    @ResponseBody
    public Jgz getJgz(){
        Jgz jgz = null;
        UserInfo userInfo = jgzService.getUserInfo();
        try {
            jgz = jgzService.queryJgzByUserPkAndDwdm(userInfo.getPk(),userInfo.getJgdm());
            if (jgz==null){
                jgz = new Jgz();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return jgz;
    }

    @TargetLogger("06020402")
    @RequiresPermissions("ROLE_VIEW")
    @RequestMapping("/excel")
    public void exportJgzList(HttpServletResponse response,@RequestParam Map<?, ?> paramMap){
        //导出默认1000行
        int pageSize = 1000;
        int pageNumber = 1;
        OutputStream os = null;
        try {
            ResultDto page = jgzService.queryListByPage(paramMap,pageNumber,pageSize);
            List list = page.getRows();

            response.setContentType("application/vnd.ms-excel");
            response.addHeader("Content-Disposition", "attachment;filename=exportJgz"+ System.currentTimeMillis() + ".xls");
            os = response.getOutputStream();

            ExportBeanExcel<Jgz> export = new ExportBeanExcel<Jgz>();
            //根据需求选择导出字段，注意数据库中带有_等字符字段修改
            //导出表头
            String[] headers = {"用户姓名","单位名称","经办人警号","经办人姓名","经办人电话","协查人警号","协查人姓名","协查人电话","入库时间","录入单位"};
            //对应字段 headers 与cols一一对应
            String[] cols = {"username","dwmc","jbrzjhm","jbrxm","jbrdh","xcrzjhm","xcrxm","xcrdh","rksj","lrdwmc"};
			
            export.exportExcel("警官证对应附件表",headers,cols,list,os);

            os.flush();
            os.close();
        } catch (Exception e) {
            logger.error(e.getMessage());
            throw new RequestEntityTooLargeException(e.getMessage());
        }
    }

    @TargetLogger("060201")
    @RequiresPermissions("ROLE_XTGL")
    @RequestMapping("/curd")
    @ResponseBody
    public Map<String,String> curd(String curdType,Jgz jgz,String xxType) throws Exception {
    	Map<String,String> resultMap = new HashMap<>();
    	String msg = null;
        if (jgz!=null){
        	if (StringUtils.equalsIgnoreCase(curdType,"insert")){
        		//valid校验需在Jgz的字段上增加校验规则，规则与表单规则保持一致
        		msg = ValidateUtil.valid(jgz);
        		if (StringUtils.isNotBlank(msg)){
        			logger.error("valid insert Jgz is error :"+msg);
                     resultMap.put("msg",msg);
                     return resultMap;
                 }
                 if(StringUtils.isNotBlank(xxType) && StringUtils.equalsIgnoreCase(xxType,"dw") && StringUtils.isNotBlank(jgz.getDwdm())){

                 }else{
                     Subject currentUser = SecurityUtils.getSubject();
                     UserInfo user = (UserInfo) currentUser.getPrincipal();
                     jgz.setUserpk(user.getPk());
                     jgz.setUsername(user.getXm());
                 }
                 Jgz jgz1 = jgzService.queryJgzByUserPkAndDwdm(jgz.getDwdm(),jgz.getUserpk());
                 if (jgz1!=null){
                     if(StringUtils.isNotBlank(xxType) && StringUtils.equalsIgnoreCase(xxType,"dw")){
                         msg = "该单位已设置使用警官证，请勿重复录入。"+jgz.getDwdm();
                     }else{
                         msg = "用户:"+jgzService.getUserInfo().getXm()+" 已设置使用警官证，请勿重复录入。";
                     }
                     resultMap.put("msg",msg);
                     return resultMap;
                 }
                 jgzService.insert(jgz);
            }else if (StringUtils.equalsIgnoreCase(curdType,"delete")){
            	if(StringUtils.isNotBlank(jgz.getPk())) {
                    jgzService.delete(jgz.getPk()); //主键删除
                }else {
                    msg="没有要删除的数据";
                    logger.error("valid delete Jgz is error :"+msg);
                    resultMap.put("msg",msg);
                    return resultMap;
                }
            }else if (StringUtils.equalsIgnoreCase(curdType,"update")){
            	msg = ValidateUtil.valid(jgz);
        		if (StringUtils.isNotBlank(msg)){
        			 logger.error("valid update Jgz is error :"+msg);
                     resultMap.put("msg",msg);
                     return resultMap;
                 }
                jgzService.updateByPrimaryKey(jgz);
            }
            msg = "操作成功";
        }else{
            msg="信息未填写";
            logger.error(msg);
        }
    	resultMap.put("msg",msg);
        return resultMap;
    }
    
}
